package com.talent.jiwen.base;

import android.app.ActivityManager;
import android.content.Context;
import android.support.multidex.MultiDex;
import android.support.multidex.MultiDexApplication;

import com.abcpen.open.api.ABCOpenApi;
import com.abcpen.open.api.resp.UserTokenResp;
import com.abcpen.pen.plugin.abcpen.ABCPenSDK;
import com.abcpen.sdk.pen.PenSDK;
import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.common.OSSLog;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.liveaa.livemeeting.sdk.biz.core.ABCLiveSDK;
import com.liveaa.livemeeting.sdk.biz.core.PrefUtils;
import com.scwang.smartrefresh.header.BezierCircleHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.talent.jiwen.BuildConfig;
import com.talent.jiwen.R;
import com.talent.jiwen.util.LogUtil;
import com.talent.jiwen.util.SPUtil;
import com.talent.jiwen.util.SystemUtil;
import com.tencent.bugly.crashreport.CrashReport;
import com.zhy.http.okhttp.OkHttpUtils;

import org.abcpen.common.util.util.ALog;
import org.abcpen.common.util.util.Utils;

import java.io.IOException;
import java.util.List;

import cn.jpush.android.api.JPushInterface;
import retrofit2.Response;


/**
 * //  ┏┓　　　┏┓
 * //┏┛┻━━━┛┻┓
 * //┃　　　　　　　┃
 * //┃　　　━　　　┃
 * //┃　┳┛　┗┳　┃
 * //┃　　　　　　　┃
 * //┃　　　┻　　　┃
 * //┃　　　　　　　┃
 * //┗━┓　　　┏━┛
 * //   ┃　　　┃   神兽保佑
 * //   ┃　　　┃   代码无BUG！
 * //   ┃　　　┗━━━┓
 * //   ┃　　　　　　　┣┓
 * //   ┃　　　　　　　┏┛
 * //   ┗┓┓┏━┳┓┏┛
 * //     ┃┫┫　┃┫┫
 * //     ┗┻┛　┗┻┛
 * <p>
 * Created by qyqx
 */


public class App extends MultiDexApplication {

    public static App instance;
    public static OSS oss;
    public static String uid;
    public static String uname;
    /**
     * @description oss对象储存
     */
    public static final String ENDPOINT = "http://oss-cn-hangzhou.aliyuncs.com";
    public static final String ACCESSKEYID = "LTAIjQyiewQ2YDls";
    public static final String ACCESSKEYSECRET = "JA3p32DsOTMsjBoNhzz1O4a3BRKCrp";
    public static final String TESTBUCKET = "xiaolanmao";

    @Override
    public void onCreate() {
        super.onCreate();
        instance=this;
        String processName = getProcessName(this);
        if (processName != null) {
            if (processName.equals("com.talent.jiwen")) {//保证只初始化一次
                initOSSConfig();
                initLogUtilAndCrashReport();
                initOkHttpUtil();
                JPushInterface.setDebugMode(true);
                JPushInterface.init(this);

                Utils.init(this);
                ALog.getConfig().setLogSwitch(true);
                PrefUtils.getInstace().init(this);
                PenSDK.getInstance().init(this);
                //自行选择智能笔类型
                PenSDK.getInstance().setPenImpl(ABCPenSDK.getInstance());
                //添加token认证
                addTokenListener();
            }
        }
    }



    public void addTokenListener() {
        //客户端为了演示功能 这边正式集成的时候 请将token获取放在服务端
        final String appid = "cbd738427f624a918cbb6c349f937bae";
        final String appSecret = "87914d183cf148df93ddd8378c32f952";
        final long expireTime = 100000000; //过期时间 token

        ABCLiveSDK.getInstance(this).getApiServer().setTokenCallBack(new ABCOpenApi.OpenApiTokenCallBack() {
            @Override
            public String refreshToken() {

//                if (!TextUtils.isEmpty(uid)) {
//                    //第三方请自行更改为自己服务器请求token 这边只是为了显示功能
//
//                    String singPub = "appId=" + appid + "&expireTime=" + expireTime + "&uid=" + uid + "&nonceStr=123456";
//                    String s = (MD5Util.getMD5String(MD5Util.getMD5String(singPub) + "&appSecret=" + appSecret)).toUpperCase();
//                    GetUserTokenReq req = new GetUserTokenReq();
//                    req.appid = appid;
//                    req.uid = uid;
//                    req.expireTime = expireTime;
//                    req.sign = s;
//                    req.nonceStr = "123456";
//                    req.nickName = "asdsad";
//                    req.avatarUrl = "http://img.zcool.cn/community/013f5958c53a47a801219c772a5335.jpg@900w_1l_2o_100sh.jpg";
//                    try {
//                        Response<UserTokenResp> userTokenRespResponse = ABCLiveSDK.getInstance(App.this).getApiServer().testGetUserToken(req);
//                        if (userTokenRespResponse != null) {
//                            ABCLiveSDK.getInstance(App.this).initToken(userTokenRespResponse.body().data);
//                            return userTokenRespResponse.body().data;
//                        }
//                    } catch (IOException e) {
//
//                    }
//                }

                ABCLiveSDK.getInstance(App.this).initToken(SPUtil.getBSToken());

                return SPUtil.getBSToken();
            }
        });

    }




    private boolean inMainProcess() {
        String packageName = getPackageName();
        String processName = SystemUtil.getProcessName(this);
        return packageName.equals(processName);
    }




    private void initOkHttpUtil(){
        OkHttpUtils.getInstance()
                .init(this)
                .debug(true, "okHttp")
                .timeout(20 * 1000);
    }


    //static 代码段可以防止内存泄露
    static {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                layout.setPrimaryColorsId(R.color.color_EEEEEE, android.R.color.white);//全局设置主题颜色
                return new BezierCircleHeader(context);
//                return new ClassicsHeader(context);//.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header，默认是 贝塞尔雷达Header
            }
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
                ClassicsFooter.REFRESH_FOOTER_NOTHING = "已经到底啦";
                return new ClassicsFooter(context).setDrawableSize(18);
//                return new BallPulseFooter(context);//.setDrawableSize(20)
            }
        });
    }




    /**
     * 初始化log是否打印
     */
    private void initLogUtilAndCrashReport(){
     if (BuildConfig.DEBUG) {
            LogUtil.isShowLog = true;
         CrashReport.initCrashReport(getApplicationContext(), "56ff362f24", true);
        } else {
         CrashReport.initCrashReport(getApplicationContext(), "56ff362f24", false);
            LogUtil.isShowLog = false;
        }

    }

    /**
     * 初始化拓展类
     * @param base
     */
    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(App.this);
    }




    private String getProcessName(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningApps = am.getRunningAppProcesses();
        if (runningApps == null) {
            return null;
        }
        for (ActivityManager.RunningAppProcessInfo proInfo : runningApps) {
            if (proInfo.pid == android.os.Process.myPid()) {
                if (proInfo.processName != null) {
                    return proInfo.processName;
                }
            }
        }
        return null;
    }

    private void initOSSConfig() {
        OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(ACCESSKEYID, ACCESSKEYSECRET);
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
        conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
        conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
        if (BuildConfig.DEBUG) {
            OSSLog.enableLog();
        }
        oss = new OSSClient(getApplicationContext(), ENDPOINT, credentialProvider, conf);
    }
    //  关闭打开的 activity
//    private static List<Activity> lists = new ArrayList<>();
//
//    public static void addActivity(Activity activity) {
//        lists.add(activity);
//    }
//
//    public static void clearActivity() {
//        if (lists != null) {
//            for (Activity activity : lists) {
//                activity.finish();
//            }
//            lists.clear();
//        }
//    }

    public static App getInstance() {
        return instance;
    }


    /**
     * 获取当前运行线程
     * @param context
     * @return
     */
    public static String getCurProcessName(Context context) {
        int pid = android.os.Process.myPid();
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : activityManager.getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return null;
    }


}
